package me.spring.cloud.components.starter.number.dynamic;

import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Set;
import org.springframework.context.annotation.Configuration;

/**
 * @description: 动态number配置
 * @author: luffy
 * @create: 2018-09-12 17:42
 **/
@Slf4j
@Configuration
public class DynamicBillNumberConfiguration implements ApplicationContextAware {
    public final static String namespaces = "bill-number";

    private ApplicationContext applicationContext;

    @ApolloConfigChangeListener(namespaces)
    private void onChange(ConfigChangeEvent changeEvent) {
        refreshProperties(changeEvent.changedKeys());
    }

    private void refreshProperties(Set<String> changedKeys) {
        log.info("Refreshing bill number configuration: {}", changedKeys);
        this.applicationContext.publishEvent(new EnvironmentChangeEvent(changedKeys));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
